'use strict'
const path = require('path')

function resolve(dir) {
  return path.join(__dirname, dir)
}

const vueConfig = require('./config')

const CompressionPlugin = require('compression-webpack-plugin')

const timeTemp = new Date().getTime()

module.exports = {
	// 基本路径
	publicPath: vueConfig.publicPath,
  // 输出文件目录
	outputDir: 'dist',
	//  放置静态资源的目录
	assetsDir: "static",
  // eslint-loader 是否在保存的时候检查
	lintOnSave: vueConfig.env.includes(process.env.ENV),
  // 如果你不需要生产环境的 source map，可以将其设置为 false 以加速生产环境构建。
  productionSourceMap: false,
  // webpack-dev-server 相关配置
  devServer: {
    host: '0.0.0.0',
		port: vueConfig.port,
		open: false,
		proxy: {
			[process.env.VUE_APP_BASE_API]: {
				target: vueConfig.devServer[process.env['ENV']],
				changeOrigin: true,
				pathRewrite: {
					['^' + process.env.VUE_APP_BASE_API]: ''
				}
			}
		},
		disableHostCheck: true
  },
  css: {
		extract: true,
    loaderOptions: {
      sass: {
        sassOptions: { outputStyle: "expanded" },
				additionalData: `@import "${vueConfig.globalScss}";`
      },
      postcss: {
        plugins: [
          // require('postcss-px2rem')({
          //   remUnit: 192//根据视觉稿，rem为px的十分之一，1920px  192 rem
          // })
        ]
      }
    }
  },
  configureWebpack: {
    name: vueConfig.title,
    output: {
      filename: `js/[name].${timeTemp}.js`,
      chunkFilename: `js/[name].${timeTemp}.js`
    },
    externals: {
      "echarts": "echarts"
    },
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    plugins: [
      // http://doc.ruoyi.vip/ruoyi-vue/other/faq.html#使用gzip解压缩静态文件
      new CompressionPlugin({
        cache: false,                   // 不启用文件缓存
        test: /\.(js|css|html)?$/i,     // 压缩文件格式
        filename: '[path].gz[query]',   // 压缩后的文件名
        algorithm: 'gzip',              // 使用gzip压缩
        minRatio: 0.8                   // 压缩率小于1才会压缩
      })
    ],
  },
  chainWebpack(config) {
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test
    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve(vueConfig.iconsPath))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve(vueConfig.iconsPath))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config
      .when(['admin', 'agent', 'shop'].includes(process.env['ENV']),
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: `chunk-libs-${timeTemp}`,
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: `chunk-commons-${timeTemp}`,
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single'),
          {
             from: path.resolve(__dirname, './public/robots.txt'), //防爬虫文件
             to: './' //到根目录下
          }
        }
      )
  }
}
